package org.wendu.wdoa.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.wendu.wdoa.common.CurrentUser;
import org.wendu.wdoa.common.WdoaConstants;
import org.wendu.wdoa.common.Result;
import org.wendu.wdoa.common.token.TokenUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class TokenVerifyFilter extends BasicAuthenticationFilter {

    public TokenVerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);

    }

    public TokenVerifyFilter(AuthenticationManager authenticationManager,
                             AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        if(this.shouldNotFilter(request)){
            chain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(WdoaConstants.HEADER_NAME_TOKEN);

        try {
            TokenUtils.verify(token);//校验token

            //校验token通过，以token为账号，token为凭证创建当前用户
            CurrentUser principal = new CurrentUser(token,null,token);

            //通过当前用户和凭证（token）创建认证信息
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(principal, token);

            SecurityContextHolder.getContext().setAuthentication(authentication);

            chain.doFilter(request, response);
        } catch (Exception e) {

            //校验token未通过，向客户端发送信息

            log.error(e.getMessage(), e);

            ObjectMapper objectMapper = new ObjectMapper();//这是一个工具对象可以实现对象json字符串互转            ;
            String jsonStr = objectMapper.writeValueAsString(
                    Result.err(Result.CODE_ERR_UNLOGINED, e.getMessage()));
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();//字符输出流，向浏览器输出
            out.print(jsonStr);
            out.flush();
            out.close();
        }


    }
}